package me.ingxin.android.tools

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.annotation.RequiresPermission
import androidx.core.content.FileProvider
import java.io.File

/**
 * 安装apk文件
 *
 * @param context     上下文
 * @param authorities FileProvider#grantUriPermissions
 */
@RequiresPermission(value = "android.permission.REQUEST_INSTALL_PACKAGES")
fun File.installApk(context: Context, authorities: String) {
    val intent = Intent().apply {
        action = Intent.ACTION_VIEW
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        addCategory(Intent.CATEGORY_DEFAULT)
    }
    val uri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        FileProvider.getUriForFile(context, authorities, this)
    } else {
        Uri.fromFile(this)
    }
    intent.setDataAndType(uri, "application/vnd.android.package-archive")
    context.startActivity(intent)
}